﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Windows.Storage;

namespace SNSComponent.Utiltiy
{
    internal static class FileUtility
    {
        const int BUFFER_LENGTH = 2048;
        public static void SaveFile(string path, Stream stream)
        {
            System.IO.IsolatedStorage.IsolatedStorageFile isf = null;
            System.IO.IsolatedStorage.IsolatedStorageFileStream fileStream = null;
            try
            {
                isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();

                string folderPath = path.Substring(0, path.LastIndexOf("\\") + 1);

                if (!isf.DirectoryExists(folderPath))
                {
                    isf.CreateDirectory(folderPath);
                }

                fileStream = isf.OpenFile(path, FileMode.OpenOrCreate);

                int count = 0;
                byte[] buffer = new byte[BUFFER_LENGTH];

                do
                {
                    count = stream.Read(buffer, 0, BUFFER_LENGTH);
                    fileStream.Write(buffer, 0, count);
                }
                while (count == BUFFER_LENGTH);

            }
            finally
            {
                if (stream != null)
                    stream.Dispose();

                if (fileStream != null)
                    fileStream.Dispose();

                if (isf != null)
                    isf.Dispose();
            }
        }

        public static T ReadFile<T>(string path, Func<Stream, T> resultHandler)
        {

            using (System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.FileExists(path))
                {
                    return resultHandler(isf.OpenFile(path, FileMode.Open));
                }
                else
                {
                    return resultHandler(null);
                }
            }

            
        }
    
        public static void DeleteFile(string path)
        {
            using (System.IO.IsolatedStorage.IsolatedStorageFile isf = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isf.FileExists(path))
                    isf.DeleteFile(path);
            }
        }
    }
}
